import { defineStore } from 'pinia'
import { userApi } from '@/utils/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    isLoggedIn: false
  }),
  
  // getters: {
  //   // 获取用户信息
  //   getUserInfo: (state) => state.userInfo,
  //   // 获取token
  //   getToken: (state) => state.token,
  //   // 检查是否已登录
  //   isAuthenticated: (state) => state.isLoggedIn
  // },
  
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = true
    },
    
    // 设置token
    setToken(token) {
      this.token = token
      localStorage.setItem('token', token)
    },
    
    // 登录
    async login(params) {
      try {
        // 这里可以调用API进行登录
        // const response = {}
        const response = await userApi.login(params)
        console.log('response', response)
        // this.setUserInfo(response.user)
        // this.setToken(response.token)
        if(response.code === 200) { 
        // 模拟登录成功
        // this.setUserInfo({ id: 1, name: 'Test User', email: 'test@example.com' })
        // this.setToken('mock-token')
        } else {
          return { success: true, isRegister: false }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, error: error.message }
      }
    },
    
    // 登出
    logout() {
      this.userInfo = null
      this.token = null
      this.isLoggedIn = false
      localStorage.removeItem('token')
    },
    
    // 初始化用户状态
    initUserState() {
      const token = localStorage.getItem('token')
      if (token) {
        this.token = token
        this.isLoggedIn = true
        // 这里可以调用API获取用户信息
      }
    }
  }
})